package com.example.buyticketlishi.view.ac;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.baselibrary.Base.BaseActivity;
import com.example.baselibrary.Utils.SelfToastUtil;
import com.example.baselibrary.Utils.StringUtil;
import com.example.baselibrary.Utils.TimeUtil;
import com.example.baselibrary.Utils.ToastUtil;
import com.example.buyticketlishi.R;
import com.example.buyticketlishi.RetrufitHelp.BaseSubscriber;
import com.example.buyticketlishi.RetrufitHelp.ExceptionHandle;
import com.example.buyticketlishi.RetrufitHelp.RetrofitClient;
import com.example.buyticketlishi.adapter.SealAdapter;
import com.example.buyticketlishi.bean.JJHSealTicketForTitleResultBean;
import com.example.buyticketlishi.bean.JJHSealTicketImforTitleBean;
import com.example.buyticketlishi.bean.JJHSealTitleBean;
import com.example.buyticketlishi.bean.LiShihandSetReserveProductRequsetBean;
import com.example.buyticketlishi.wightview.KouLingBottom;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity {

    private LinearLayout mGallery;
    private TextView timeDate;
    private List<JJHSealTitleBean.DataBean> titleList;
    private List<JJHSealTicketForTitleResultBean.DataBean> pointImforList;
    private LayoutInflater mInflater;
    private TextView sealTitle;
    private TextView seletcView;
    private SealAdapter sealAdapter;
    private JJHSealTicketImforTitleBean sealTicketImforTitleBean;
    private RecyclerView recyclerViewList;
    private Button btBuyNow;
    private Button btSetting;
    private ImageView IvSetting;
    private Button upMove;
    private Button downMove;

    //产品预订需要用到的数据
    private LiShihandSetReserveProductRequsetBean productRequsetBean;

    // 数量 和 金额 统计
    private int sealNumber = 0;
    private double sealMoney = 0;
    private TextView tvSealNumber;
    private TextView tvSealMoney;
    private List<JJHSealTicketForTitleResultBean.DataBean> selectOverData;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (titleList == null) {
            titleList = new ArrayList<>();
        }

    }

    @Override
    protected int getView() {
        return R.layout.activity_main;
    }

    @Override
    public void init() {
        //对标题进行设置
        mInflater = LayoutInflater.from(this);

        mGallery = (LinearLayout) findViewById(R.id.id_gallery);
        timeDate = findViewById(R.id.tv_main_data_time);
        upMove = findViewById(R.id.bt_main_up_move);
        downMove = findViewById(R.id.bt_main_down_move);
        btBuyNow = (Button) findViewById(R.id.bt_main_buy_now);
        btSetting = (Button) findViewById(R.id.bt_setting_point);

        IvSetting = (ImageView) findViewById(R.id.iv_setting);

        tvSealNumber = findViewById(R.id.tv_main_seal_all_number);
        tvSealMoney = findViewById(R.id.tv_main_seal_all_money);

        recyclerViewList = (RecyclerView) findViewById(R.id.rv_seal_list);

        if (pointImforList == null) {
            pointImforList = new ArrayList<>();
        }
        sealAdapter = new SealAdapter(this, pointImforList, Base_URL, headers);
        // 给recycleView 设置布局
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerViewList.setLayoutManager(linearLayoutManager);
        recyclerViewList.setAdapter(sealAdapter);

        timeDate.setText(TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_DATE_EN));

        if (sealTicketImforTitleBean == null) {
            sealTicketImforTitleBean = new JJHSealTicketImforTitleBean();
        }
        sealTicketImforTitleBean.setSaleChannelType(1);
        sealTicketImforTitleBean.setScenicTicketProductCategory(1);
        sealTicketImforTitleBean.setArriveDT(TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_TIME_EN_NEW));

        //这个是 订单生成的对象
        if (productRequsetBean == null) {
            productRequsetBean = new LiShihandSetReserveProductRequsetBean();
        }

        tvSealNumber.setText(sealNumber + "");
        tvSealMoney.setText("¥" + sealMoney);


//        getNetTitle();

        doThing();

        upMove.setVisibility(View.GONE);
        downMove.setVisibility(View.GONE);

        // 数据选择 后，将数据拿出来
        sealAdapter.setDataSelectListener(new SealAdapter.DataSelectListener() {
            @Override
            public void dataSelect(List<JJHSealTicketForTitleResultBean.DataBean> data) {
//                for (int i = 0; i < data.size(); i++) {
//                    LogUtil.d(data.get(i).toString());
//                }

                selectOverData = data;
                sealNumber = 0;
                sealMoney = 0;
                for (int i = 0; i < data.size(); i++) {
                    if (!StringUtil.isNullOrEmpty(data.get(i).getSaleSum())) {
                        //如果销售数量不为空，那么去统计
                        sealNumber = sealNumber + Integer.parseInt(data.get(i).getSaleSum());
                        sealMoney = sealMoney + Integer.parseInt(data.get(i).getSaleSum()) * (data.get(i).getPrice());
                    }

                    tvSealNumber.setText(sealNumber + "");
                    tvSealMoney.setText("¥" + keepTwoDecimalPlaces(sealMoney));
                }
            }
        });
    }

    /**
     * 保留两位小数
     *
     * @param number
     * @return
     */
    private String keepTwoDecimalPlaces(double number) {
        String result = new DecimalFormat("0.00").format(number);
        return result;
    }


    private void doThing() {

        btBuyNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //数据准备好，才去跳转
                DataPrePar();
            }
        });

        upMove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recyclerViewList.smoothScrollToPosition(0);
            }
        });

        downMove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recyclerViewList.smoothScrollToPosition(pointImforList.size() - 1);
            }
        });

//        btSetting.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                (new KouLingBottom(MainActivity.this)).show();
//            }
//        });

        IvSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                (new KouLingBottom(MainActivity.this)).show();
            }
        });

    }

    private void DataPrePar() {

        //点击立即预订，需要先判断对象是否成立  productRequsetBean
        if (selectOverData == null) {
            SelfToastUtil.getInstance().show("请先选择游玩类型");
            return;
        } else {
            // 如果统计的票数为0  那么也不行
            if (sealNumber == 0) {
                SelfToastUtil.getInstance().show("请先选择游玩类型");
                return;
            }
        }
        // 如果不为空，那么就进行下一步
        List<LiShihandSetReserveProductRequsetBean.ProductParamListBean> productParamListBeanList = new ArrayList<>();
        for (int i = 0; i < selectOverData.size(); i++) {
            //如果数据不为空，那么就去生成数据
            if (!StringUtil.isNullOrEmpty(selectOverData.get(i).getSaleSum())) {

                LiShihandSetReserveProductRequsetBean.ProductParamListBean productParamListBean = new LiShihandSetReserveProductRequsetBean.ProductParamListBean();
                productParamListBean.setCertificateFlag(selectOverData.get(i).getCertificateFlag());
                productParamListBean.setArriveDT(selectOverData.get(i).getArriveDT());
                productParamListBean.setScenicTicketId(selectOverData.get(i).getScenicTicketId());
                productParamListBean.setShiftsId(0L);
                productParamListBean.setSaleSum(Integer.parseInt(selectOverData.get(i).getSaleSum()));
                productParamListBean.setCustomerDiscountType(Integer.parseInt(selectOverData.get(i).getCustomerDiscountType()));
                //  这个是 时段标识
                productParamListBean.setBookByTimeFlag(selectOverData.get(i).getBookByTimeFlag());
                productParamListBean.setScenicTicketName(selectOverData.get(i).getScenicTicketName());

                //新加年龄标记
                productParamListBean.setMinAge(selectOverData.get(i).getMinAge());
                productParamListBean.setMaxAge(selectOverData.get(i).getMaxAge());

                if (productParamListBean.getBookByTimeFlag().equals("Y")) {
                    if (selectOverData.get(i).getMinResidueSum() == 0) {
                        SelfToastUtil.getInstance().show("时段票，请先选择时段");
                        return;
                    }

                    if (Integer.parseInt(selectOverData.get(i).getSaleSum()) > selectOverData.get(i).getMinResidueSum()) {
                        //如果 购买的票，大于最小的时段选着，那么就说明 有的时段票不满足条件，告知客户
                        SelfToastUtil.getInstance().show("所选择的票种数量，超出了时段票剩余票数，请确定时段票信息");
                        return;
                    }
                }

                List<LiShihandSetReserveProductRequsetBean.ProductParamListBean.TimeControlParamListBean> listBeans = new ArrayList<>();
                if (selectOverData.get(i).getTimeData() != null) {

                    for (int i1 = 0; i1 < selectOverData.get(i).getTimeData().size(); i1++) {
                        LiShihandSetReserveProductRequsetBean.ProductParamListBean.TimeControlParamListBean timeControlParamListBean = new LiShihandSetReserveProductRequsetBean.ProductParamListBean.TimeControlParamListBean();
                        timeControlParamListBean.setProjectId(Long.parseLong(selectOverData.get(i).getTimeData().get(i1).getProjectId()));
                        timeControlParamListBean.setOrdTimeControlId(Long.parseLong(selectOverData.get(i).getTimeData().get(i1).getOrdTimeControlId()));
                        listBeans.add(timeControlParamListBean);
                    }
                    productParamListBean.setTimeControlParamList(listBeans);
                }
                productParamListBeanList.add(productParamListBean);
            }
            //将所有数据装载到需要传送的对象里面
            productRequsetBean.setProductParamList(productParamListBeanList);

        }

        productRequsetBean.setSaleChannelType(2);
        //打印模式，占时不知道
        productRequsetBean.setPrintTicketMode(1);
        // 装载完毕，要确定所选票中是否有实名票，有的话要跳转到实名页面，没有就到支付
//        for (int i = 0; i < productRequsetBean.getProductParamList().size(); i++) {
//            if (productRequsetBean.getProductParamList().get(i).getCertificateFlag() == 1) {
        //如果有一个需要实名制，那么就来搞实名制
        intent = new Intent(MainActivity.this, InformationActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("allData", productRequsetBean);
        bundle.putString("allNumber", sealNumber + "");
        bundle.putString("allMoney", sealMoney + "");
        intent.putExtra("myData", bundle);
        startActivity(intent);
//        return;
//            }
//        }


        // 如果循环结束，还没有实名制，那就是没有实名制，那么就去走不需要实名制
//        intent1 = new Intent(MainActivity.this, PaySelectActivity.class);
//        Bundle bundle = new Bundle();
//        bundle.putParcelable("allData", productRequsetBean);
//        intent.putExtras(bundle);
//        startActivity(intent1);

    }

    private void getNetTitle() {
        //进入界面网络请求  加载数据
        RetrofitClient.getInstance(MainActivity.this, Base_URL, headers).JJHSealTicketTitle(new BaseSubscriber<JJHSealTitleBean>(MainActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                iosLoadDialog.dismiss();
                SelfToastUtil.getInstance().show(e.code + " " + e.message);
            }

            @Override
            public void onNext(JJHSealTitleBean jjhSealTitleBean) {
                if (jjhSealTitleBean.getCode().equals("200")) {
                    // 请求成功对页面进行显示
                    // 对list 清空
                    iosLoadDialog.dismiss();
                    titleList.clear();
                    for (int i = 0; i < jjhSealTitleBean.getData().size(); i++) {
                        titleList.add(jjhSealTitleBean.getData().get(i));
                    }

//                    for (int i = 0; i < 3; i++) {
//                        if (titleList.size() < 3) {
//                            JJHSealTitleBean.DataBean dataBean = new JJHSealTitleBean.DataBean();
//                            dataBean.setScenicSpotsName("景点待开发");
//                            titleList.add(dataBean);
//                        }
//                    }
                    //然后去更新title
                    updateTitleFace();
                    //针对title 下的 list
                    updateListPoint(titleList.get(0));
                } else {
                    //对失败进行反馈
                    iosLoadDialog.dismiss();
                    SelfToastUtil.getInstance().show(jjhSealTitleBean.getMessage());
                }

            }
        });
    }

    private void updateTitleFace() {
        mGallery.removeAllViews();
        for (int i = 0; i < titleList.size(); i++) {
            View view = mInflater.inflate(R.layout.sale_title_item, mGallery, false);
            sealTitle = view.findViewById(R.id.tv_seal_title_hol);
            // 选中是蓝底白字，未选中蓝字白纸
            if (i == 0) {
                seletcView = sealTitle;
                sealTitle.setTextColor(getResources().getColor(R.color.color_white));
                sealTitle.setBackgroundResource(R.drawable.shape_seal_change);
                //一进来，要赋值默认值
//                scenicTicketId = titleList.get(i).getScenicSpotsId() + "";
            } else {
                sealTitle.setTextColor(getResources().getColor(R.color.color_bule_title));
                sealTitle.setBackgroundResource(R.drawable.shape_title);
            }
            sealTitle.setText(titleList.get(i).getScenicSpotsName());
            sealTitle.setId(i);
            sealTitle.setOnClickListener(new OnClickListenerImpl());
            mGallery.addView(view);

        }
    }

    private class OnClickListenerImpl implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            //每一次点击就要修改界面
            changeFeacTitle((TextView) v);

            switch (v.getId()) {
                default:
                    // 去刷新列表
//                    scenicTicketId = titleList.get(v.getId()).getScenicSpotsId() + "";
                    //来来去去切换的时候，数据清空
                    tvSealNumber.setText("0");
                    tvSealMoney.setText("¥" + "0.00");
                    updateListPoint(titleList.get(v.getId()));
                    break;
            }

        }
    }

    private void changeFeacTitle(TextView view) {
        if (!seletcView.equals(view)) {
            view.setTextColor(getResources().getColor(R.color.color_white));
            view.setBackgroundResource(R.drawable.shape_seal_change);

            seletcView.setTextColor(getResources().getColor(R.color.color_bule_title));
            seletcView.setBackgroundResource(R.drawable.shape_title);

            seletcView = view;
        }
    }

    private void updateListPoint(JJHSealTitleBean.DataBean dataBean) {
        if (dataBean.getScenicSpotsId() == 0) {
            pointImforList.clear();
            sealAdapter.notifyDataSetChanged();
            return;
        }
        sealTicketImforTitleBean.setScenicSpotsId(dataBean.getScenicSpotsId());
        RetrofitClient.getInstance(MainActivity.this, Base_URL, headers).findUserSaleProduct(sealTicketImforTitleBean,
                new BaseSubscriber<JJHSealTicketForTitleResultBean>(MainActivity.this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        ToastUtil.showToast(e.code + " " + e.message);
//                        updateTitleFace();
                    }

                    @Override
                    public void onNext(JJHSealTicketForTitleResultBean jjhSealTicketForTitleResultBean) {
                        if (jjhSealTicketForTitleResultBean.getCode().equals("200")) {
                            pointImforList.clear();
                            for (int i = 0; i < jjhSealTicketForTitleResultBean.getData().size(); i++) {
                                pointImforList.add(jjhSealTicketForTitleResultBean.getData().get(i));
                                //添加假数据，防止为空
                                pointImforList.get(i).setSaleSum(0 + "");
                                pointImforList.get(i).setShiftsId("");
                                pointImforList.get(i).setCustomerDiscountType("1");
                                pointImforList.get(i).setTimeShow("");
                                pointImforList.get(i).setArriveDT(TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_DATE_EN));
                            }
                            if (pointImforList.size() <= 0) {
                                SelfToastUtil.getInstance().show("该景点暂无可游玩项目，请选择其他景点");
                            }

//                            if (pointImforList.size() > 7) {
//                                upMove.setVisibility(View.VISIBLE);
//                                downMove.setVisibility(View.VISIBLE);
//                            } else {
//                                upMove.setVisibility(View.GONE);
//                                downMove.setVisibility(View.GONE);
//                            }

                            sealAdapter.notifyDataSetChanged();
                        } else {
                            //对失败进行反馈
                            ToastUtil.showToast(jjhSealTicketForTitleResultBean.getMessage());
                        }

                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();

        getNetTitle();

        sealNumber = 0;
        sealMoney = 0;
        tvSealNumber.setText("0");
        tvSealMoney.setText("¥" + "0.00");
        productRequsetBean = null;
        selectOverData = null;

        if (selectOverData == null) {
            selectOverData = new ArrayList<>();
        }

        if (productRequsetBean == null) {
            productRequsetBean = new LiShihandSetReserveProductRequsetBean();
        }
    }
}
